package com.project.service.impl;

import com.project.mapper.ProductMapper;
import com.project.pojo.Product;
import com.project.service.ProductService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean updateStock(int num) {
        log.info("更新商品库存开始");
        Product product = productMapper.selectById(1);
        product.setStock(product.getStock() - num);
        if (productMapper.updateById(product)>0){
            return true;
        }
        return false;
    }


    @Override
    public synchronized boolean updateStock2(int num) {
        log.info("更新商品库存开始");
        Product product = productMapper.selectById(1);
        product.setStock(product.getStock() - num);
        product.setVersion(product.getVersion() + 1);
        if (productMapper.updateById(product)>0){
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//必须加事务回滚，否则for update的sql语句执行完事务就提交了
    public boolean updateStock3(int num) {
        //必须加id的where筛选条件，否则会锁表
        log.info("更新商品库存开始");
        Product product = productMapper.selectByIdForUpdate(1);
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        product.setStock(product.getStock() - num);
        product.setVersion(product.getVersion() + 1);
        if (productMapper.updateById(product)>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteProduct(Long id) {
        int i = productMapper.deleteById(id);
        if (i>0){
            return true;
        }
        return false;
    }

    @Override
    public List<Product> list() {
        List<Product> products = productMapper.selectList(null);
        return products;
    }

    @Override
    public boolean insertRedis() {
        redisTemplate.opsForValue().set("name","张三");
        System.out.println(redisTemplate.opsForValue().get("name"));
        return true;
    }

}